<template>
  <div class="user-home-container">
    <div>
      <div class="userHead">
        <el-row :gutter="20" class="user-profile-row">
          <!-- 左侧用户信息卡片 -->
          <el-col :xs="24" :sm="24" :md="14" :lg="14" :xl="14">
            <el-card class="user-info-card" shadow="hover">
              <div class="user-profile-content">
                <div class="avatar-section">
                  <el-avatar 
                    :size="120" 
                    :src="data.touristInfo.avatar" 
                    fit="cover"
                    class="user-avatar"
                  >
                    <img
                      src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                    />
                  </el-avatar>
                  <div class="action-buttons" v-if="auth.getToken() && (!route.params.id || route.params.id == userStore.userInfo.id)">
                    <el-button
                      type="primary"
                      size="default"
                      round
                      @click="$router.push('/changInfo')"
                      class="profile-btn"
                    >
                      <el-icon><Edit /></el-icon>
                      编辑资料
                    </el-button>
                    <el-button
                      type="default"
                      size="default"
                      round
                      @click="centerDialogVisible = true"
                      class="profile-btn"
                    >
                      <el-icon><Lock /></el-icon>
                      修改密码
                    </el-button>
                  </div>
                </div>
                <div class="user-details">
                  <h2 class="user-name">{{ data.userName }}</h2>
                  <el-descriptions :column="1" size="large" class="user-desc">
                    <el-descriptions-item>
                      <template #label>
                        <el-icon><Link /></el-icon>
                        个人主页
                      </template>
                      <span v-if="data.homePage == 0" class="no-data">暂时没有个人主页哟~</span>
                      <el-link 
                        v-else 
                        :href="data.homePage" 
                        target="_blank" 
                        type="primary"
                        :underline="false"
                      >
                        {{ data.homePage }}
                      </el-link>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template #label>
                        <el-icon><Briefcase /></el-icon>
                        工作
                      </template>
                      <span v-if="data.job == 0" class="no-data">暂时没有工作哟</span>
                      <span v-else>{{ data.job }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template #label>
                        <el-icon><School /></el-icon>
                        学校/专业
                      </template>
                      {{ data.schoolName + ' / ' + data.majorName }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template #label>
                        <el-icon><ChatDotRound /></el-icon>
                        个人简介
                      </template>
                      {{ data.touristInfo.description }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 右侧成就统计卡片 -->
          <el-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10">
            <el-card class="achievement-card" shadow="hover">
              <template #header>
                <div class="achievement-header">
                  <el-icon class="achievement-icon"><Trophy /></el-icon>
                  <span class="achievement-title">个人成就</span>
                </div>
              </template>
              
              <!-- 阅读统计 -->
              <div class="read-stats">
                <el-statistic 
                  title="文章总阅读量" 
                  :value="data.touristInfo.readNum"
                  suffix="次"
                  class="read-statistic"
                >
                  <template #prefix>
                    <el-icon style="color: #409eff"><View /></el-icon>
                  </template>
                </el-statistic>
              </div>
              
              <el-divider />
              
              <!-- 内容统计 -->
              <el-row :gutter="12" class="content-stats">
                <el-col :span="6">
                  <el-statistic 
                    title="文章" 
                    :value="data.touristInfo.articleNum"
                    class="content-statistic"
                  >
                    <template #prefix>
                      <el-icon style="color: #67c23a"><Document /></el-icon>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic 
                    title="成果" 
                    :value="data.touristInfo.achievementNum"
                    class="content-statistic"
                  >
                    <template #prefix>
                      <el-icon style="color: #e6a23c"><Medal /></el-icon>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic 
                    title="资源" 
                    :value="data.touristInfo.resourceNum"
                    class="content-statistic"
                  >
                    <template #prefix>
                      <el-icon style="color: #f56c6c"><FolderOpened /></el-icon>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic 
                    title="任务" 
                    :value="data.touristInfo.taskNum || 0"
                    class="content-statistic"
                  >
                    <template #prefix>
                      <el-icon style="color: #909399"><List /></el-icon>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
              
              <el-divider />
              
              <!-- 其他信息 -->
              <div class="other-info">
                <el-descriptions :column="1" size="default">
                  <el-descriptions-item label="研究方向">
                    <el-tag type="info" size="default">{{ data.domainName }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="加入时间">
                    <el-text type="info" size="default">
                      <el-icon><Calendar /></el-icon>
                      {{ data.touristInfo.createdAt }}
                    </el-text>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div class="userBody">
        <el-tabs 
          v-model="activeIndex" 
          @tab-change="handleTabChange"
          class="user-tabs"
        >
          <el-tab-pane label="文章" name="1">
            <articleTable />
          </el-tab-pane>
          <el-tab-pane label="成果" name="2">
            <achievement />
          </el-tab-pane>
          <el-tab-pane label="资源" name="3">
            <resourceTable />
          </el-tab-pane>
          <el-tab-pane label="任务" name="4">
            <taskTable />
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-dialog
        v-model="centerDialogVisible"
        title="修改密码"
        width="450px"
        center
        @closed="resetPasswordForm"
      >
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
          label-position="left"
        >
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
              clearable
            />
          </el-form-item>
          <div class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitPasswordChange"
              :loading="passwordLoading"
            >
              确认修改
            </el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import Cookies from 'js-cookie'
import md5 from 'js-md5'
import { getUserInfo } from '@/api/user'
import { onMounted, provide, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { 
  Avatar, 
  ChatDotRound, 
  Trophy, 
  Edit, 
  Lock, 
  Link, 
  Briefcase, 
  School, 
  View, 
  Document, 
  Medal, 
  FolderOpened, 
  Calendar,
  List 
} from '@element-plus/icons-vue'
import { TweenMax } from 'gsap'
import auth from '../../utils/auth'
import { useStore } from '@/store'
import base from '../../api/base'
import { Post, postCode } from '@/api/myApi'
import axios from '../../utils/Axios'
import { getTouristInfo } from '@/api/tourist'
import { ElMessage } from 'element-plus'
import articleTable from '../userTable/articleTable.vue'
import achievement from '../userTable/achievement.vue'
import resourceTable from '../userTable/resourceTable.vue'
import taskTable from '../userTable/taskTable.vue'

const passwordFormRef = ref(null)
const passwordLoading = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 密码验证规则
const validateOldPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入当前密码'))
  } else {
    callback()
  }
}

const validateNewPassword = (rule, value, callback) => {
  const patt = /(?=.*\d)(?=.*[a-zA-Z])^.{6,20}$/
  if (!value) {
    callback(new Error('请输入新密码'))
  } else if (!patt.test(value)) {
    callback(new Error('密码需要在6-20位之间并包含字母和数字'))
  } else {
    // 如果确认密码已经输入，重新验证确认密码
    if (passwordForm.confirmPassword) {
      passwordFormRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次输入新密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [{ validator: validateOldPassword, trigger: 'blur' }],
  newPassword: [{ validator: validateNewPassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
}

// 重置密码表单
function resetPasswordForm() {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
  passwordLoading.value = false
}

// 提交密码修改
function submitPasswordChange() {
  passwordFormRef.value?.validate(valid => {
    if (valid) {
      passwordLoading.value = true
      try {
        const oldPasswordMd5 = md5(md5(passwordForm.oldPassword))
        const newPasswordMd5 = md5(passwordForm.newPassword)
        axios
          .post('/backapi/changePassword', {
            userId: data.touristInfo.id,
            oldPassword: oldPasswordMd5,
            newPassword: newPasswordMd5,
          })
          .then(res => {
            if (res.success) {
              ElMessage({
                message: res.message,
                type: 'success',
                duration: 5 * 1000,
              })
              centerDialogVisible.value = false
            } else {
              ElMessage({
                message: res.message,
                type: 'error',
                duration: 5 * 1000,
              })
            }
          })
      } catch (error) {
        console.error('提交表单出错:', error)
        ElMessage({
          message: '提交表单出错',
          type: 'error',
          duration: 5 * 1000,
        })
      }
      passwordLoading.value = false
    }
  })
}

const helloData = reactive({
  code: '',
  sendStatus: false,
  sendEmail: '发送验证码',
  loading: false,
  helloDataRule: {
    password: [{ validator: validatorCode, trigger: 'blur' }],
  },
})

// 处理tab切换
function handleTabChange(tabName) {
  activeIndex.value = tabName
}

const centerDialogVisible = ref(false)

function validatorPassword(rule, value, callback) {
  if (!Cookies.get('yourPassword')) {
    const patt = /(?=.*\d)(?=.*[a-zA-Z])^.{6,20}$/
    if (patt.test(value) && value && !Cookies.get('yourPassword')) {
      callback()
    } else {
      callback(new Error('密码需要在6-20位之间并包含字母和数字'))
    }
  }
  callback()
}

function validatorNum(rule, value, callback) {
  const treg = /^[0-9]\d*$|^0$/
  if (
    value &&
    treg.test(value) === true &&
    (value.length === 12 || value.length === 7)
  ) {
    callback()
  } else {
    callback(new Error('请输入12位学号'))
  }
}

function validatorCode(rule, value, callback) {}

const querySearch = (value, cb) => {
  let autoCompleteResult
  if (!value || value.indexOf('@') >= 0) {
    autoCompleteResult = []
  } else {
    autoCompleteResult = [
      '@gmail.com',
      '@163.com',
      '@qq.com',
      '@aliyun.com',
    ].map(domain => `${value}${domain}`)
  }
  cb(autoCompleteResult)
}
const handleSelect = item => {
  findData.email = item
}
const findData = reactive({
  stuNumFind: Cookies.get('yourStuNum') || '',
  email: '',
  newPassWord: '',
  nextTip: false,
  findRules: {
    stuNumFind: [{ validator: validatorNum, required: true, trigger: 'blur' }],
    email: [
      {
        type: 'email',
        required: true,
        message: 'Please input correct email address',
        trigger: 'blur',
      },
    ],
    newPassWord: [
      { validator: validatorPassword, required: true, trigger: 'blur' },
    ],
  },
})
const submitFind = formEl => {
  console.log(formEl)
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      Post(base.forgetPassword, {
        id: findData.stuNumFind,
        email: findData.email,
        password: md5(findData.newPassWord),
      }).then(res => {
        if (res.success) {
          findData.nextTip = true
        }
      })
    }
  })
  // centerDialogVisible.value = false
}
const uploadCode = () => {
  if (findData.email === '') {
    ElMessage({
      type: 'error',
      message: '邮箱不存在，请返回上一步',
    })
    return
  }
  helloData.sendStatus = true
  let time = 60
  const clearnTime = setInterval(() => {
    time--
    if (time == 0) {
      clearInterval(clearnTime)
      helloData.sendEmail = '重新发送'
      helloData.sendStatus = false
    } else {
      helloData.sendEmail = `${time}s后重新发送`
    }
  }, 1000)
  const params = {
    email: findData.email,
  }
  postCode(base.uploadCode, params.email)
    .then(() => {})
    .catch(() => {
      // clearInterval(clearnTime)
      // helloData.sendEmail = '重新发送'
      // helloData.sendStatus = false
    })
  ElMessage({
    type: 'success',
    message: '发送成功,请查看邮箱 !!!',
  })
}
const userStore = useStore()
const data = reactive({
  touristInfo: {},
  schoolName: '',
  majorName: '',
  userName: '',
  job: '',
  homePage: '',
  domainName: '',
})
const activeIndex = ref('1')
const route = useRoute()
provide(
  'isMyself',
  auth.getToken() &&
    (!route.params.id || route.params.id == userStore.userInfo.id)
)

// 获取任务数量的函数
const getTaskCount = async (userId) => {
  try {
    const { getTaskList } = await import('../userTable/task')
    const taskRes = await getTaskList({
      user_id: userId,
      page: 1,
      limit: 1
    })
    return taskRes.total_count || 0
  } catch (error) {
    console.error('获取任务数量失败:', error)
    return 0
  }
}

if (
  auth.getToken() &&
  (!route.params.id || route.params.id == userStore.userInfo.id)
) {
  getUserInfo().then(async res => {
    // console.log(res)
    res = res.data
    data.touristInfo = res
    data.schoolName = res.school.name
    data.majorName = res.major.name
    data.userName = res.user.name
    findData.stuNumFind = res.id
    data.homePage = res.homePage
    data.job = res.job

    if (data.homePage == null) {
      data.homePage = 0
    }
    if (data.job == null) {
      data.job = 0
    }

    data.domainName = res.domain.name
    // 获取任务数量
    data.touristInfo.taskNum = await getTaskCount(res.id)
    // store.state.userInfo.tx = res.avatar
    Cookies.set('userTx', res.avatar, { expires: 1 })
    userStore.SET_TX(res.avatar)
  })
} else {
  getTouristInfo(route.params.id).then(async res => {
    data.touristInfo = res
    data.schoolName = res.school.name
    data.majorName = res.major.name
    data.userName = res.user.name

    data.homePage = res.homePage
    data.job = res.job
    data.resume = res.resume
    if (data.homePage == null) {
      data.homePage = 0
    }
    if (data.job == null) {
      data.job = 0
    }
    if (data.resume == null) {
      data.resume = 0
    }
    data.domainName = res.domain_info.name
    // 获取任务数量
    data.touristInfo.taskNum = await getTaskCount(route.params.id)
  })
}
onMounted(() => {
  TweenMax.from('.headLeft', 1, {
    duration: 2.5,
    ease: 'elastic.out(1, 0.3)',
    x: -200,
  })
  TweenMax.from('.headRight', 1, {
    duration: 2.5,
    ease: 'elastic.out(1, 0.3)',
    y: 200,
  })
})
</script>

<style scoped lang="less">
/* 主容器样式 - 避免被固定导航栏遮挡 */
.user-home-container {
  padding-top: 80px; /* 导航栏高度60px + 20px间距 */
  min-height: calc(150vh - 60px); /* 增加最小高度，确保出现滚动条 */
  overflow-y: auto;
  overflow-x: hidden;
  
  /* 美化滚动条 */
  &::-webkit-scrollbar {
    width: 8px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
    transition: background 0.3s ease;
    
    &:hover {
      background: #a8a8a8;
    }
  }
  
  /* Firefox 滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* Tabs样式 */
::v-deep .user-tabs {
  .el-tabs__header {
    margin: 0;
    border-bottom: 2px solid #e4e7ed;
  }
  
  .el-tabs__nav-wrap {
    display: flex;
    justify-content: center;
  }
  
  .el-tabs__item {
    font-size: 20px;
    font-weight: 600;
    letter-spacing: 8px;
    padding: 0 30px;
    height: 50px;
    line-height: 50px;
    color: #606266;
    transition: all 0.3s ease;
    
    &:hover {
      color: #409eff;
    }
    
    &.is-active {
      color: #409eff;
      font-weight: 700;
    }
    
    @media (max-width: 1000px) {
      letter-spacing: 2px;
      font-size: 16px;
      padding: 0 20px;
    }
  }
  
  .el-tabs__active-bar {
    background-color: #409eff;
    height: 3px;
  }
  
  .el-tabs__content {
    padding-top: 20px;
    max-height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
    
    /* 美化内容区滚动条 */
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f8f9fa;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #d1d5db;
      border-radius: 3px;
      transition: background 0.3s ease;
      
      &:hover {
        background: #9ca3af;
      }
    }
    
    /* Firefox 滚动条样式 */
    scrollbar-width: thin;
    scrollbar-color: #d1d5db #f8f9fa;
  }
}

.userHead {
  width: 90%;
  margin: 20px auto 0;
  
  .user-profile-row {
    margin-bottom: 20px;
  }
  
  .user-info-card {
    height: 100%;
    border-radius: 12px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
    }
    
    ::v-deep .el-card__body {
      padding: 16px;
    }
    
    .user-profile-content {
      display: flex;
      gap: 16px;
      
      .avatar-section {
          display: flex;
          flex-direction: column;
          align-items: center;
          min-width: 120px;
          
          .user-avatar {
            margin-bottom: 12px;
            border: 3px solid #f0f2f5;
          transition: all 0.3s ease;
          
          &:hover {
            border-color: #409eff;
            transform: scale(1.05);
          }
        }
        
        .action-buttons {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 6px;
            width: 100%;
          
          .profile-btn {
            width: 100%;
            font-size: 14px;
            padding: 10px 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .el-icon {
              margin-right: 6px;
              font-size: 16px;
            }
          }
        }
      }
      
      .user-details {
        flex: 1;
        
        .user-name {
          margin: 0 0 10px 0;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          background: linear-gradient(135deg, #409eff, #67c23a);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
        
        .user-desc {
          font-size: 15px;
          
          .el-descriptions__label {
            font-weight: 500;
            color: #606266;
            font-size: 15px;
            
            .el-icon {
              margin-right: 6px;
              color: #909399;
            }
          }
          
          .el-descriptions__content {
            color: #303133;
            font-size: 15px;
          }
          
          .no-data {
            color: #c0c4cc;
            font-style: italic;
          }
        }
      }
    }
  }
  
  .achievement-card {
    height: 100%;
    border-radius: 12px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
    }
    
    ::v-deep .el-card__body {
      padding: 16px;
    }
    
    ::v-deep .el-card__header {
      padding: 12px 16px;
    }
    
    .achievement-header {
      display: flex;
      align-items: center;
      justify-content: center;
      
      .achievement-icon {
        margin-right: 8px;
        font-size: 20px;
        color: #e6a23c;
      }
      
      .achievement-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .read-stats {
      text-align: center;
      margin-bottom: 12px;
      
      .read-statistic {
        .el-statistic__content {
          font-size: 24px;
          font-weight: 600;
          color: #409eff;
        }
      }
    }
    
    .content-stats {
      margin: 12px 0;
      
      .content-statistic {
        text-align: center;
        
        .el-statistic__content {
          font-size: 28px;
          font-weight: bold;
          color: #409eff;
        }
        
        .el-statistic__head {
          font-size: 16px;
          color: #909399;
          margin-bottom: 6px;
        }
      }
    }
    
    .other-info {
      .el-descriptions__label {
        font-weight: 500;
        color: #606266;
      }
      
      .el-tag {
        border-radius: 12px;
      }
      
      .el-text {
        display: flex;
        align-items: center;
        
        .el-icon {
          margin-right: 4px;
        }
      }
    }
  }
}

.userBody {
  width: 80%;
  margin: 10px auto 0;
}

@media (max-width: 1200px) {
  .userHead {
    width: 95%;
    
    .user-info-card {
      .user-profile-content {
        flex-direction: column;
        align-items: center;
        text-align: center;
        
        .avatar-section {
          margin-bottom: 20px;
          
          .action-buttons {
            flex-direction: row;
            justify-content: center;
            align-items: center;
            gap: 12px;
            
            .profile-btn {
              width: auto;
              min-width: 100px;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
        }
        
        .user-details {
          .user-name {
            text-align: center;
          }
        }
      }
    }
    
    .achievement-card {
      margin-top: 20px;
      
      .content-stats {
        .el-col {
          margin-bottom: 16px;
        }
        
        .content-statistic {
          margin-bottom: 0;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .userHead {
    width: 100%;
    margin: 10px auto 0;
    
    .user-info-card {
      .user-profile-content {
        .avatar-section {
          .user-avatar {
            width: 80px;
            height: 80px;
          }
          
          .action-buttons {
            flex-direction: column;
            align-items: center;
            
            .profile-btn {
              width: 100%;
              font-size: 11px;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
        }
        
        .user-details {
          .user-name {
            font-size: 20px;
          }
        }
      }
    }
    
    .achievement-card {
      .read-stats {
        .read-statistic {
          .el-statistic__content {
            font-size: 20px;
          }
        }
      }
      
      .content-stats {
        .el-col {
          margin-bottom: 12px;
        }
        
        .content-statistic {
          .el-statistic__content {
            font-size: 16px;
          }
          
          .el-statistic__head {
            font-size: 11px;
          }
        }
      }
    }
  }
  
  .userBody {
    width: 100%;
    margin: 10px auto 0;
  }
}
</style>
